import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import '../models/task.dart';
import 'package:intl/intl.dart';

class GraphicPage extends StatefulWidget {
  final List<Task> tasks;

  const GraphicPage({
    Key? key,
    required this.tasks,
  }) : super(key: key);

  @override
  _GraphicPageState createState() => _GraphicPageState();
}

class _GraphicPageState extends State<GraphicPage> {
  // 当前选择的月份
  DateTime _selectedMonth = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题
                const Text(
                  'Graphic',
                  style: TextStyle(
                    fontSize: 28,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF232751),
                  ),
                ),
                const SizedBox(height: 24),

                // 优先级气泡图部分
                _buildPrioritySection(),
                const SizedBox(height: 32),

                // 活动图表部分
                _buildActivitySection(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 优先级部分
  Widget _buildPrioritySection() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题和图例
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                'Priority',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF232751),
                ),
              ),
              Row(
                children: [
                  _buildLegendItem(const Color(0xFFF2938C), 'Personal'),
                  const SizedBox(width: 12),
                  _buildLegendItem(const Color(0xFF8A85FF), 'Private'),
                  const SizedBox(width: 12),
                  _buildLegendItem(const Color(0xFF7ED6E3), 'Secret'),
                ],
              ),
            ],
          ),
          const SizedBox(height: 8),
          const Text(
            'Task Perday',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 16),

          // 气泡图
          SizedBox(
            height: 220,
            child: _buildScatterChart(),
          ),
        ],
      ),
    );
  }

  // 图例项
  Widget _buildLegendItem(Color color, String label) {
    return Row(
      children: [
        Container(
          width: 12,
          height: 12,
          decoration: BoxDecoration(
            color: color,
            shape: BoxShape.circle,
          ),
        ),
        const SizedBox(width: 4),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  // 散点图 (模拟气泡图)
  Widget _buildScatterChart() {
    const daysOfWeek = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
    final spots = _generateScatterSpots();

    return ScatterChart(
      ScatterChartData(
        scatterSpots: spots,
        minX: 0,
        maxX: 7,
        minY: 1,
        maxY: 11,
        borderData: FlBorderData(show: false),
        gridData: FlGridData(
          show: true,
          drawHorizontalLine: true,
          horizontalInterval: 2,
          drawVerticalLine: true,
          getDrawingHorizontalLine: (value) {
            return FlLine(
              color: const Color(0xFFEAEAEA),
              strokeWidth: 1,
              dashArray: [5, 5],
            );
          },
          getDrawingVerticalLine: (value) {
            return FlLine(
              color: const Color(0xFFEAEAEA),
              strokeWidth: 1,
              dashArray: [5, 5],
            );
          },
        ),
        titlesData: FlTitlesData(
          show: true,
          topTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          rightTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              getTitlesWidget: (value, meta) {
                if (value < 0 || value >= daysOfWeek.length || value % 1 != 0) {
                  return const SizedBox.shrink();
                }
                return Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child: Text(
                    daysOfWeek[value.toInt()],
                    style: const TextStyle(
                      color: Color(0xFF232751),
                      fontSize: 12,
                    ),
                  ),
                );
              },
            ),
          ),
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 28,
              interval: 2,
              getTitlesWidget: (value, meta) {
                if (value % 2 != 0) {
                  return const SizedBox.shrink();
                }
                return Text(
                  value.toInt().toString().padLeft(2, '0'),
                  style: const TextStyle(
                    color: Color(0xFF232751),
                    fontSize: 12,
                  ),
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  // 生成气泡图数据点
  List<ScatterSpot> _generateScatterSpots() {
    // 这里可以根据实际任务数据生成点，现在用模拟数据
    final personalColor = const Color(0xFFF2938C);
    final privateColor = const Color(0xFF8A85FF);
    final secretColor = const Color(0xFF7ED6E3);

    return [
      // Personal tasks (红色)
      ScatterSpot(0.9, 8, dotPainter: FlDotCirclePainter(color: personalColor, radius: 8)),
      ScatterSpot(2.1, 6, dotPainter: FlDotCirclePainter(color: personalColor, radius: 8)),
      ScatterSpot(2.9, 8, dotPainter: FlDotCirclePainter(color: personalColor, radius: 8)),
      ScatterSpot(4.1, 4, dotPainter: FlDotCirclePainter(color: personalColor, radius: 8)),
      ScatterSpot(4.9, 6, dotPainter: FlDotCirclePainter(color: personalColor, radius: 8)),
      ScatterSpot(6.1, 8, dotPainter: FlDotCirclePainter(color: personalColor, radius: 8)),

      // Private tasks (紫色)
      ScatterSpot(0.1, 4, dotPainter: FlDotCirclePainter(color: privateColor, radius: 8)),
      ScatterSpot(1.1, 10, dotPainter: FlDotCirclePainter(color: privateColor, radius: 8)),
      ScatterSpot(2.9, 6, dotPainter: FlDotCirclePainter(color: privateColor, radius: 8)),
      ScatterSpot(3.1, 2, dotPainter: FlDotCirclePainter(color: privateColor, radius: 8)),
      ScatterSpot(3.9, 8, dotPainter: FlDotCirclePainter(color: privateColor, radius: 8)),
      ScatterSpot(6.1, 6, dotPainter: FlDotCirclePainter(color: privateColor, radius: 8)),

      // Secret tasks (蓝色)
      ScatterSpot(1.9, 2, dotPainter: FlDotCirclePainter(color: secretColor, radius: 8)),
      ScatterSpot(2.9, 10, dotPainter: FlDotCirclePainter(color: secretColor, radius: 8)),
      ScatterSpot(3.9, 2, dotPainter: FlDotCirclePainter(color: secretColor, radius: 8)),
      ScatterSpot(5.1, 4, dotPainter: FlDotCirclePainter(color: secretColor, radius: 8)),
    ];
  }

  // 活动部分
  Widget _buildActivitySection() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Your Activity',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: Color(0xFF232751),
            ),
          ),
          const SizedBox(height: 16),

          // 月份选择器
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              IconButton(
                icon: const Icon(Icons.chevron_left),
                onPressed: () {
                  setState(() {
                    _selectedMonth = DateTime(
                      _selectedMonth.year,
                      _selectedMonth.month - 1,
                      1,
                    );
                  });
                },
              ),
              Text(
                DateFormat('MMMM yyyy').format(_selectedMonth),
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF232751),
                ),
              ),
              IconButton(
                icon: const Icon(Icons.chevron_right),
                onPressed: () {
                  setState(() {
                    _selectedMonth = DateTime(
                      _selectedMonth.year,
                      _selectedMonth.month + 1,
                      1,
                    );
                  });
                },
              ),
            ],
          ),
          const SizedBox(height: 16),

          // 活动柱状图
          SizedBox(
            height: 220,
            child: _buildActivityBarChart(),
          ),
        ],
      ),
    );
  }

  // 活动柱状图
  Widget _buildActivityBarChart() {
    return BarChart(
      BarChartData(
        alignment: BarChartAlignment.spaceBetween,
        barGroups: _generateBarGroups(),
        gridData: FlGridData(
          show: true,
          drawHorizontalLine: true,
          drawVerticalLine: false,
          horizontalInterval: 1,
          getDrawingHorizontalLine: (value) {
            return FlLine(
              color: const Color(0xFFEAEAEA),
              strokeWidth: 1,
            );
          },
        ),
        borderData: FlBorderData(show: false),
        titlesData: FlTitlesData(
          show: true,
          leftTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          rightTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          topTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
          bottomTitles: const AxisTitles(
            sideTitles: SideTitles(showTitles: false),
          ),
        ),
        barTouchData: BarTouchData(enabled: false),
      ),
    );
  }

  // 生成柱状图数据
  List<BarChartGroupData> _generateBarGroups() {
    // 这里可以根据实际任务数据生成柱状图，现在用模拟数据
    final days = List.generate(10, (index) => index + 1);
    
    return days.map((day) {
      // 随机生成高度，实际中应该根据任务数据计算
      final double personalHeight = _getRandomHeight(day);
      final double workHeight = _getRandomHeight(day);
      final double privateHeight = _getRandomHeight(day);
      
      return BarChartGroupData(
        x: day,
        barRods: [
          BarChartRodData(
            toY: personalHeight + workHeight + privateHeight,
            width: 20,
            borderRadius: BorderRadius.zero,
            rodStackItems: [
              BarChartRodStackItem(
                0, 
                privateHeight, 
                const Color(0xFF8A85FF),
              ),
              BarChartRodStackItem(
                privateHeight, 
                privateHeight + workHeight, 
                const Color(0xFF7ED6E3),
              ),
              BarChartRodStackItem(
                privateHeight + workHeight, 
                privateHeight + workHeight + personalHeight, 
                const Color(0xFFF2938C),
              ),
            ],
          ),
        ],
      );
    }).toList();
  }
  
  // 辅助方法：获取随机高度（模拟数据）
  double _getRandomHeight(int day) {
    // 让中间几天有较高的活动，模拟图片中的效果
    if (day >= 4 && day <= 8) {
      return 1.0 + (day % 3) * 0.5;
    }
    return 0.5 + (day % 3) * 0.3;
  }
} 